<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'

import { onLoad, onShow } from '@dcloudio/uni-app'
import { calculateDistance } from '@/utils/http'
// import Header from '@/pagesMember/address/header.vue'
const systemInfo = uni.getSystemInfoSync()
const { safeAreaInsets, windowHeight, screenWidth } = systemInfo
// rpx 转 px 工具函数
const rpxToPx = (rpx: number) => (rpx / 750) * screenWidth

// 初始高度（800rpx）
const initialMainHeight = rpxToPx(800)

// 响应式地图高度
const mainHeight = ref(initialMainHeight)
const mapLoaded = ref(true)

// ======== 滚动事件处理 ========
const onScrolltolower = () => {
  const listTargetRpx = 1000
  const listHeightPx = rpxToPx(listTargetRpx)

  // 计算新地图高度：窗口高 - 列表高
  mainHeight.value = Math.max(windowHeight - listHeightPx, 200)

  // 重建地图
  mapLoaded.value = false
  nextTick(() => {
    setTimeout(() => {
      mapLoaded.value = true
    }, 50)
  })
}

const scrolltoupper = () => {
  // 还原初始高度
  mainHeight.value = initialMainHeight

  // 重建地图
  mapLoaded.value = false
  nextTick(() => {
    setTimeout(() => {
      mapLoaded.value = true
    }, 50)
  })
}
const close = () => {}
const submit = () => {}

const addressMap = ref('')
const markers = ref({} as any)

const setMarkers = (res: any) => {
  markers.value = res.map((item: any) => {
    return {
      title: item.address, // 标记点名称（可选，部分平台显示在 infoWindow）
      address: item.address, // 自定义字段，非标准 marker 属性（可用于传递数据）
      alpha: 1, // 透明度，1 表示不透明（合法值）
      width: 30, // 图标宽度（单位 px）
      height: 30, // 图标高度
      id: item.id, // ✅ 修正：原为 'tiem.id'，应为 'item.id'
      latitude: item.latitude, // 纬度（必须）
      longitude: item.longitude, // 经度（必须）
      iconPath: '../../static/img/red_marker.png', // 图标路径（建议使用绝对路径或本地资源）
      iconTapPath: '../../static/img/red_marker.png', // 点击后的图标（可选）
    }
  })
}

// 引入百度地图API

const bmap = require('../../static/js/bmap-wx.min.js')
const BMapWX = bmap.BMapWX
//    这个地方是你在百度地图中申请的ak
var BMap = new BMapWX({ ak: 'hOtF9JR4wCD5SSQGKhddv4IsHildEpVF' })

const detailInfo = ref<any>({
  latitude: null,
  longitude: null,
  address: '',
})

const poisList = ref([] as any[])

onLoad(() => {
  init()
})

const init = () => {
  if (!detailInfo.value.latitude || !detailInfo.value.longitude) {
    uni.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success: (data: any) => {
        detailInfo.value.latitude = data.latitude
        detailInfo.value.longitude = data.longitude
        getCurrentLocation(detailInfo.value)
      },
    })
  } else {
    getCurrentLocation(detailInfo.value)
  }
}

const getCurrentLocation = (e: any) => {
  const { latitude, longitude } = e
  if (!latitude || !longitude) return
  // 调用reverseGeocode方法进行反向地理编码
  BMap.regeocoding({
    location: `${latitude},${longitude}`,
    coordtype: 'gcj02ll', // 输入坐标是 GCJ-02 火星坐标
    ret_coordtype: 'gcj02ll', // 返回结果也使用 GCJ-02 坐标
    radius: 1000, // 搜索半径 1000 米
    success: (data: any) => {
      console.log('成功:', data)

      poisList.value = data.originalData.result.pois.map((item: any) => {
        return {
          ...item,
          address: item.addr,
          longitude: item.point.x,
          latitude: item.point.y,
        }
      })
      setMarkers(data.wxMarkerData)
      console.log(markers.value)
      // 成功回调处理逻辑
    },
    fail: (data: any) => {
      console.error('失败:', data)
      // 失败回调处理逻辑
    },
  })
}

const markertap = (info: any) => {
  // const storeId = markers.value.find((v:any) => v.id === info.detail.markerId)?.storeId
  // uni.navigateTo({ url: '/pagesStore/detail/detail?id=' + storeId })
}

const searchMap = (e: any) => {
  const query = e.value.trim()
  if (!query) return
  activeIndex.value = 0
  BMap.suggestion({
    query: query,
    coordtype: 'gcj02ll', // 输入坐标是 GCJ-02 火星坐标
    ret_coordtype: 'gcj02ll', // 返回结果也使用 GCJ-02 坐标
    output: 'json',
    success: (data: any) => {
      poisList.value = data.result.map((item: any) => ({
        name: item.name,
        address: item.address || '',
        latitude: item.location.lat,
        longitude: item.location.lng,
        uid: item.uid,
        distance: calculateDistance(
          detailInfo.value.latitude,
          detailInfo.value.longitude,
          item.location.lat,
          item.location.lng,
        ),
      }))
    },
    fail: (err: any) => {
      console.error('失败：', err)
      wx.showToast({ title: '搜索失败', icon: 'none' })
    },
  })
}

const activeIndex = ref(0)
const checkhandler = (record: any, index: number) => {
  activeIndex.value = index
  console.log(record)

  detailInfo.value.latitude = record.latitude
  detailInfo.value.longitude = record.longitude

  markers.value = [record].map((item: any, idx: number) => {
    return {
      title: item.address, // 标记点名称（可选，部分平台显示在 infoWindow）
      address: item.address, // 自定义字段，非标准 marker 属性（可用于传递数据）
      alpha: 1, // 透明度，1 表示不透明（合法值）
      width: 30, // 图标宽度（单位 px）
      height: 30, // 图标高度
      id: idx, // ✅ 修正：原为 'tiem.id'，应为 'item.id'
      latitude: item.latitude, // 纬度（必须）
      longitude: item.longitude, // 经度（必须）
      iconPath: '../../static/img/red_marker.png', // 图标路径（建议使用绝对路径或本地资源）
      iconTapPath: '../../static/img/red_marker.png', // 点击后的图标（可选）
    }
  })

  console.log(markers.value)
}
</script>

<template>
  <view class="wrap-page" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="top">
      <view class="cancel" @click="close">取消</view>
      <view class="address-text">
        {{ detailInfo.address || '' }}
      </view>
      <view
        class="confirm"
        @click="submit"
        :style="{ backgroundColor: true ? 'rgba(0, 0, 0, 0.2)' : '#42b983' }"
        >确定</view
      >
    </view>
    <!-- <Header :title="'个人中心'" /> -->

    <scroll-view class="wrap-scroll" scroll-y :show-scrollbar="false" enable-back-to-top>
      <view class="wrap-main" :style="{ height: mainHeight + 'px' }">
        <map
          class="map"
          id="map"
          style="width: 100%; height: 100%"
          :latitude="detailInfo.latitude"
          :longitude="detailInfo.longitude"
          :scale="14"
          :show-location="false"
          :markers="markers"
          @markertap="markertap"
        ></map>
      </view>
      <view class="wrap-list">
        <view class="search-input">
          <uni-search-bar
            radius="5"
            placeholder="请输入关键词"
            clearButton="auto"
            cancelButton="none"
            @confirm="searchMap"
          />
        </view>
        <scroll-view
          class="primary"
          scroll-y
          :show-scrollbar="false"
          enable-back-to-top
          @scrolltoupper="scrolltoupper"
          @scrolltolower="onScrolltolower"
        >
          <view
            class="list-item"
            @tap="checkhandler(item, index)"
            v-for="(item, index) in poisList"
            :key="index"
          >
            <view class="item-con">
              <view class="item-address">{{ item.address }}</view>
              <view class="item-info">
                <view class="distance">{{ item.distance }}m</view>
                <view>|</view>
                <view class="name">{{ item.name }}</view>
              </view>
            </view>
            <view class="item-checked" v-if="activeIndex === index">
              <text class="iconfont icon-gouxuan2"></text>
            </view>
          </view>
        </scroll-view>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
}
.wrap-page {
  display: flex;
  flex-direction: column;

  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 99;
  background-color: #fff;
  .top {
    position: absolute;
    width: 100%;
    height: 80rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 40rpx;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0.2);
    color: #fff;
    z-index: 999;

    .confirm {
      height: 60rpx;
      line-height: 60rpx;
      padding: 0 20rpx;
      border-radius: 10rpx;
      background-color: #42b983;
    }

    .address-text {
      width: 55vw;
      text-align: center;
      overflow: hidden;
      word-wrap: break-word;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
  }

  .wrap-scroll {
    .wrap-main {
      width: 100%;
      height: 800rpx;
    }
    .wrap-list {
      height: 1000rpx;
      display: flex;
      flex-direction: column;
      .search-input {
        padding: 0 20rpx;
      }
      .list-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        padding: 20rpx;
        border-bottom: 1px solid $border-color;
        .item-con {
          flex: 1;
          display: flex;
          flex-direction: column;
          .item-address {
            font-size: $font-size;
          }
        }

        .item-checked {
          display: flex;
          justify-content: center;
          align-items: center;
          .icon-gouxuan2 {
            color: $color;
          }
        }

        .item-info {
          padding-top: 20rpx;
          display: flex;
          flex-direction: row;

          justify-content: flex-start;
          font-size: $font-size;
          color: #333;

          .distance,
          .name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .distance {
            color: #888;
            font-size: $font-size;
          }

          .name {
            color: #888;
            font-weight: 500;
            flex: 1;
            font-size: $font-size;
          }

          // 分隔线
          > view:nth-child(2) {
            color: #ddd;
            font-size: $font-size;
          }
        }
      }
    }
  }
}
</style>
